{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://pymt.readthedocs.io\"><img style=\"float: left\" src=\"../media/powered-by-logo-header.png\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Coastline Evolution Model\n",
    "\n",
    "* Link to this notebook: https://github.com/csdms/pymt/blob/master/docs/demos/cem.ipynb\n",
    "* Install command: `$ conda install notebook pymt_cem`\n",
    "* Download local copy of notebook:\n",
    "\n",
    "  `$ curl -O https://raw.githubusercontent.com/csdms/pymt/master/docs/demos/cem.ipynb`\n",
    "\n",
    "This example explores how to use a BMI implementation using the CEM model as an example.\n",
    "\n",
    "### Links\n",
    "* [CEM source code](https://github.com/csdms/cem-old/tree/mcflugen/add-function-pointers): Look at the files that have *deltas* in their name.\n",
    "* [CEM description on CSDMS](http://csdms.colorado.edu/wiki/Model_help:CEM): Detailed information on the CEM model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Interacting with the Coastline Evolution Model BMI using Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some magic that allows us to view images within the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Import the `Cem` class, and instantiate it. In Python, a model with a BMI will have no arguments for its constructor. Note that although the class has been instantiated, it's not yet ready to be run. We'll get to that later!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pymt.models\n",
    "cem = pymt.models.Cem()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Even though we can't run our waves model yet, we can still get some information about it. *Just don't try to run it.* Some things we can do with our model are get the names of the input variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.output_var_names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.input_var_names"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can also get information about specific variables. Here we'll look at some info about wave direction. This is the main input of the Cem model. Notice that BMI components always use [CSDMS standard names](http://csdms.colorado.edu/wiki/CSDMS_Standard_Names). The CSDMS Standard Name for wave angle is,\n",
    "\n",
    "    \"sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity\"\n",
    "\n",
    "Quite a mouthful, I know. With that name we can get information about that variable and the grid that it is on (it's actually not a one)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "angle_name = 'sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity'\n",
    "\n",
    "print(\"Data type: %s\" % cem.get_var_type(angle_name))\n",
    "print(\"Units: %s\" % cem.get_var_units(angle_name))\n",
    "print(\"Grid id: %d\" % cem.get_var_grid(angle_name))\n",
    "print(\"Number of elements in grid: %d\" % cem.get_grid_number_of_nodes(0))\n",
    "print(\"Type of grid: %s\" % cem.get_grid_type(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "OK. We're finally ready to run the model. Well not quite. First we initialize the model with the BMI **initialize** method. Normally we would pass it a string that represents the name of an input file. For this example we'll pass **None**, which tells Cem to use some defaults."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "args = cem.setup(number_of_rows=100, number_of_cols=200, grid_spacing=200.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.initialize(*args)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before running the model, let's set a couple input parameters. These two parameters represent the wave height and wave period of the incoming waves to the coastline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "cem.set_value(\"sea_surface_water_wave__height\", 2.)\n",
    "cem.set_value(\"sea_surface_water_wave__period\", 7.)\n",
    "cem.set_value(\"sea_surface_water_wave__azimuth_angle_of_opposite_of_phase_velocity\", 0. * np.pi / 180.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The main output variable for this model is *water depth*. In this case, the CSDMS Standard Name is much shorter:\n",
    "\n",
    "    \"sea_water__depth\"\n",
    "\n",
    "First we find out which of Cem's grids contains water depth. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_id = cem.get_var_grid('sea_water__depth')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the *grid_id*, we can now get information about the grid. For instance, the number of dimension and the type of grid (structured, unstructured, etc.). This grid happens to be *uniform rectilinear*. If you were to look at the \"grid\" types for wave height and period, you would see that they aren't on grids at all but instead are scalars."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_type = cem.get_grid_type(grid_id)\n",
    "grid_rank = cem.get_grid_ndim(grid_id)\n",
    "print('Type of grid: %s (%dD)' % (grid_type, grid_rank))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because this grid is uniform rectilinear, it is described by a set of BMI methods that are only available for grids of this type. These methods include:\n",
    "* get_grid_shape\n",
    "* get_grid_spacing\n",
    "* get_grid_origin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "spacing = np.empty((grid_rank, ), dtype=float)\n",
    "\n",
    "shape = cem.get_grid_shape(grid_id)\n",
    "cem.get_grid_spacing(grid_id, out=spacing)\n",
    "\n",
    "print('The grid has %d rows and %d columns' % (shape[0], shape[1]))\n",
    "print('The spacing between rows is %f and between columns is %f' % (spacing[0], spacing[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Allocate memory for the water depth grid and get the current values from `cem`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "z = np.empty(shape, dtype=float)\n",
    "cem.get_value('sea_water__depth', out=z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here I define a convenience function for plotting the water depth and making it look pretty. You don't need to worry too much about it's internals for this tutorial. It just saves us some typing later on."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_coast(spacing, z):\n",
    "    import matplotlib.pyplot as plt\n",
    "    \n",
    "    xmin, xmax = 0., z.shape[1] * spacing[0] * 1e-3\n",
    "    ymin, ymax = 0., z.shape[0] * spacing[1] * 1e-3\n",
    "\n",
    "    plt.imshow(z, extent=[xmin, xmax, ymin, ymax], origin='lower', cmap='ocean')\n",
    "    plt.colorbar().ax.set_ylabel('Water Depth (m)')\n",
    "    plt.xlabel('Along shore (km)')\n",
    "    plt.ylabel('Cross shore (km)')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It generates plots that look like this. We begin with a flat delta (green) and a linear coastline (y = 3 km). The bathymetry drops off linearly to the top of the domain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_coast(spacing, z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Right now we have waves coming in but no sediment entering the ocean. To add some discharge, we need to figure out where to put it. For now we'll put it on a cell that's next to the ocean."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Allocate memory for the sediment discharge array and set the discharge at the coastal cell to some value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "qs = np.zeros_like(z)\n",
    "qs[0, 100] = 1250"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The CSDMS Standard Name for this variable is:\n",
    "\n",
    "    \"land_surface_water_sediment~bedload__mass_flow_rate\"\n",
    "\n",
    "You can get an idea of the units based on the quantity part of the name. \"mass_flow_rate\" indicates mass per time. You can double-check this with the BMI method function **get_var_units**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.get_var_units('land_surface_water_sediment~bedload__mass_flow_rate')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.time_step, cem.time_units, cem.time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Set the bedload flux and run the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for time in tqdm(range(3000)):\n",
    "    cem.set_value('land_surface_water_sediment~bedload__mass_flow_rate', qs)\n",
    "    cem.update_until(time)\n",
    "\n",
    "cem.get_value('sea_water__depth', out=z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cem.get_value('sea_water__depth', out=z)\n",
    "plot_coast(spacing, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val = np.empty((5, ), dtype=float)\n",
    "cem.get_value(\"basin_outlet~coastal_center__x_coordinate\", val)\n",
    "val / 100."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's add another sediment source with a different flux and update the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "qs[0, 150] = 1500\n",
    "for time in tqdm(range(3750)):\n",
    "    cem.set_value('land_surface_water_sediment~bedload__mass_flow_rate', qs)\n",
    "    cem.update_until(time)\n",
    "    \n",
    "cem.get_value('sea_water__depth', out=z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_coast(spacing, z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we shut off the sediment supply completely."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "qs.fill(0.)\n",
    "for time in tqdm(range(4000)):\n",
    "    cem.set_value('land_surface_water_sediment~bedload__mass_flow_rate', qs)\n",
    "    cem.update_until(time)\n",
    "    \n",
    "cem.get_value('sea_water__depth', out=z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_coast(spacing, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
